package com.chezhujie.www.controller;


import com.chezhujie.www.domain.Czjawardon;
import com.chezhujie.www.domain.Czjawardstock;
import com.chezhujie.www.domain.Czjbranch;
import com.chezhujie.www.domain.Czjroulette;
import com.chezhujie.www.domain.vo.CzjawardstockVO;
import com.chezhujie.www.service.CzjawardonService;
import com.chezhujie.www.service.CzjawardstockService;
import com.chezhujie.www.service.CzjrouletteService;
import com.chezhujie.www.service.Czjtop3Service;
import com.sys.user.base.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import com.sys.core.page.Pagination;


@Controller
@RequestMapping("awardon")
public class CzjawardonController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(CzjawardonController.class);
	public CzjawardonController() {
	}
	
	
 	/**
	 * czj_roulette  优惠新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteAdd.do")
	public String czjrouletteAdd(HttpServletRequest request, ModelMap model) {		
		
		String rouletteId = request.getParameter("rouletteId");
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("ext3", rouletteId);
		Czjroulette czjroulette = czjrouletteService.getCzjrouletteByAct(param);	
		if(czjroulette==null){
			czjroulette = new Czjroulette();
			czjroulette.setRouletteId(rouletteId);
		}else{
		  czjroulette.setRouletteId(rouletteId);	
		}			
		model.addAttribute("czjroulette", czjroulette);
      setDict(model);
		return "roulette/czjrouletteEdit";
	}	
	
	/**
	 * czj_roulette  轮盘保存
	 * 
	 * @param czjroulette
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteSave.do")
	public String save(Czjroulette czjroulette, 
			@RequestParam(value = "first", required = false)  MultipartFile first,
			@RequestParam(value = "second", required = false) MultipartFile second,		
			HttpServletRequest request, ModelMap model) throws Exception{ 
		try {
			//路径
			String pathRoot = request.getSession().getServletContext()
					.getRealPath("");
			String path = "";				
			// 第一张头像
			if (!first.isEmpty() && first.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid + "." + "jpg";
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				first.transferTo(new File(pathRoot + path));					
				//更新才删
				String jpgPic = czjroulette.getImgPath();					
				if(jpgPic != null && jpgPic.length()>5){
					jpgPic = jpgPic.substring(1, jpgPic.length());
				}
				deleteFile(pathRoot + jpgPic);
				//更新才设置图片路径				
				czjroulette.setImgPath(path);
			}
			// 第二张头像
			if (!second.isEmpty() && second.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid + "." + "jpg";
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				second.transferTo(new File(pathRoot + path));					
				//更新才删
				String jpgPic = czjroulette.getImgUrl();					
				if(jpgPic != null && jpgPic.length()>5){
					jpgPic = jpgPic.substring(1, jpgPic.length());
				}
				deleteFile(pathRoot + jpgPic);
				//更新才设置图片路径				
				czjroulette.setImgUrl(path);
			}	
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("ext3", czjroulette.getRouletteId());
			Czjroulette  czjroulette1 = czjrouletteService.getCzjrouletteByAct(param);	
			
			if(czjroulette1!=null&&!czjroulette1.getRouletteId().equals("")){
				// 编辑	
				czjroulette.setExt3(czjroulette.getRouletteId());
				czjroulette.setRouletteId(czjroulette1.getRouletteId());
				czjrouletteService.updateCzjroulette(czjroulette);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_roulette  优惠", "rouletteId="+czjroulette.getrouletteId()));
			} else {
				// 新增
				czjroulette.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				czjroulette.setExt1("0");
				czjroulette.setExt3(czjroulette.getRouletteId());
				czjrouletteService.insertCzjroulette(czjroulette);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_roulette  优惠", "rouletteId="+czjroulette.getrouletteId()));
			}
						
   		} catch (Exception e) {
   			log.error("czjroulette save error:", e); 
            throw e;
   		}

			 return "redirect:czjawardonList.do?rouletteId="+czjroulette.getExt3();  

	}	
 
	/**
	 * czj_awardstock 奖品库编辑页面
	 * 
	 * @param awardstockId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardstockEdit.do")
	public void czjawardstockEdit(String awardstockId, 
			String rouletteId,
			HttpServletRequest request,
			HttpServletResponse response,
			ModelMap model) throws Exception{
      try {
          String message = request.getParameter("message");                  
          request.setAttribute("message", message);
   		Map<String, Object> param = new HashMap<String, Object>();
   		param.put("awardstockId", awardstockId);
         CzjawardstockVO czjawardstockVO = czjawardstockService.getCzjawardstockVO(param); 
         
         param.put("rouletteId", rouletteId);
         Czjbranch czjbranch = czjrouletteService.getCzjrouletteByAwardstockId(param);
         if(czjbranch!=null){
        	 czjawardstockVO.setIslimit(Integer.valueOf(czjbranch.getExt1()));
        	 czjawardstockVO.setAutoNum(Integer.valueOf(czjbranch.getCountnum()));
        	 czjawardstockVO.setMissNum(Integer.valueOf(czjbranch.getExt2()));
        	 czjawardstockVO.setLastNum(czjawardstockVO.getAutoNum()-czjawardstockVO.getMissNum());
         }else{
        	 czjawardstockVO.setIslimit(0);
        	 czjawardstockVO.setAutoNum(0);
        	 czjawardstockVO.setMissNum(0);
        	 czjawardstockVO.setLastNum(0);
        	 czjawardstockVO.setMessage(0);
         }             
         jsonResult(1, "", "获取奖品信息成功", czjawardstockVO, response);      
         model.addAttribute("actionEdit", request.getParameter("actionEdit"));
         setDict(model);
         } catch (Exception e) {
   			log.error("czjawardstock edit error:", e); 
            throw e;
   		}
		
	}
	
	
	
 	/**
	 * czj_awardon 奖品线上新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardonAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		String shopId = request.getParameter("shopId");
		Czjawardon czjawardon = new Czjawardon();
		if(shopId!=null){
			czjawardon.setShopId(shopId);
		}
        Map<String, Object> param2 = new HashMap<String, Object>();
        List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param2);
                 
        model.addAttribute("czjawardstocks", czjawardstocks); 		
		model.addAttribute("czjawardon", czjawardon);
      setDict(model);
		return "awardon/czjawardonEdit";
	}

	/**
	 * czj_awardon 奖品线上保存
	 * 
	 * @param czjawardon
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardonSave.do")
	public String save(Czjawardon czjawardon, 
			HttpServletRequest request, ModelMap model) throws Exception{     
		try {	
			
			if(czjawardon.getAwardonId()!=null&&!czjawardon.getAwardonId().equals("")){
				// 编辑
				czjawardonService.updateCzjawardon(czjawardon);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_awardon 奖品线上", "awardonId="+czjawardon.getAwardonId()));
			} else {
				// 新增
				czjawardon.setCreatetime(new Date());
				czjawardonService.insertCzjawardon(czjawardon);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_awardon 奖品线上", "awardonId="+czjawardon.getAwardonId()));
			}
   		} catch (Exception e) {
   			log.error("czjawardon save error:", e); 
            throw e;
   		}
      
		return "redirect:czjawardonList.do?rouletteId="+czjawardon.getShopId();
	}

	/**
	 * czj_awardon 奖品线上删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("czjawardonDelete.do")
	public String delete(@RequestParam("ids") List<String> awardonIdList,String shopId) throws Exception{
		try {
         if (awardonIdList != null) {
   			czjawardonService.deleteCzjawardon(awardonIdList);
   		}
         } catch (Exception e) {
   			log.error("czjawardon delete error:", e); 
            throw e;
   		}
		if(shopId ==null || "".equals(shopId)){			
			return "redirect:czjawardonList.do";
		}else{
			return "redirect:czjawardonList.do?rouletteId="+shopId;
			
		}
	}
	 
	/**
	 * czj_awardon 奖品线上编辑页面
	 * 
	 * @param awardonId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardonEdit.do")
	public String edit(String awardonId, HttpServletRequest request, ModelMap model) throws Exception{
      try {
		  model.addAttribute("failed", request.getParameter("failed"));
		  model.addAttribute("success", request.getParameter("success"));
  		String shopId = request.getParameter("rouletteId");   	  
          String message = request.getParameter("message");                  
          request.setAttribute("message", message);
   		Map<String, Object> param = new HashMap<String, Object>();
   		param.put("awardonId", awardonId);
         Czjawardon czjawardon = czjawardonService.getCzjawardon(param);
         
         Map<String, Object> param2 = new HashMap<String, Object>();
         List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param2);
                  
         model.addAttribute("czjawardstocks", czjawardstocks); 
   		model.addAttribute("czjawardon", czjawardon);
  		if(shopId!=null){
  			czjawardon.setShopId(shopId);
  		}
         model.addAttribute("actionEdit", request.getParameter("actionEdit"));
         setDict(model);
         } catch (Exception e) {
   			log.error("czjawardon edit error:", e); 
            throw e;
   		}
		return "awardon/czjawardonEdit";
	}

	/**
	 * czj_awardon 奖品线上详情
	 * 
	 * @param awardonId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardonDetail.do")
	public String detail(String awardonId, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
      try {
      		Map<String, Object> param = new HashMap<String, Object>();
      		param.put("awardonId", awardonId);
            Czjawardon czjawardon = czjawardonService.getCzjawardon(param);
      		model.addAttribute("czjawardon", czjawardon);
            setDict(model);
            } catch (Exception e) {
   			log.error("czjawardon detail error:", e); 
            throw e;
   		  }
		return "awardon/czjawardonView";
	}
	 
	/**
	 * czj_awardon 奖品线上查询（分页）
	 * 
	 * @param czjawardon
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardonList.do")
	public String listPage(Czjawardon czjawardon, Integer pageNo, String order,
			String sort,HttpServletRequest request, ModelMap model) throws Exception{
      try {   
   		if (pageNo == null)
   			pageNo = 1;
	        String shopId = request.getParameter("rouletteId");
	        if(shopId==null){
	        	shopId = request.getParameter("rouleoffId");
	        }
	        request.setAttribute("shopId", shopId);
	        czjawardon.setShopId(shopId);
         Pagination pagination = czjawardonService.getCzjawardonList(toMap(czjawardon), 20, pageNo,
   				order, sort);

         
   		model.addAttribute("pagination", pagination);
         setDict(model);
         } catch (Exception e) {
			log.error("czjawardon listPage error:", e); 
         throw e;
		   }
		return "awardon/czjawardonList";
	}
	 
	/**
	 * czj_awardon 奖品线上查询
	 * 
	 * @param czjawardon
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardonList1.do")
	public String list(Czjawardon czjawardon, HttpServletRequest request, ModelMap model) throws Exception{
      try {
   		Map<String,Object> map = czjawardonService.getCzjawardonList(toMap(czjawardon));
   		model.addAttribute("list", map.get("rows"));
   		model.addAttribute("total", map.get("total"));
         setDict(model);
         } catch (Exception e) {
   			log.error("czjawardon list error:", e); 
            throw e;
   		}
		return "awardon/czjawardonList";
	}
	
	/**
	 * czj_awardon  图片广告详情
	 * 
	 * @param awardonId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("queryImgOrder.do")
	public void detail1111(String ext1, String shopId, String awardonId, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
      try {
      		Map<String, Object> param = new HashMap<String, Object>();
      		param.put("ext1", ext1); 
      		param.put("shopId", shopId); 
            Czjawardon czjawardon = czjawardonService.queryImgOrder(param);
                          
            //插入时
      		if("".equals(awardonId)){  
      			     if(czjawardon !=null){
      			    	jsonResult(1,"","重复的顺序",0,response);  
      			     }else{
      			    	jsonResult(1,"","可以添加",1,response);  
      			     }      				      			         
	      		}
      		//更新时      		
      		if(!"".equals(awardonId)){
          		//查询自己
          		Map<String, Object> paramMy = new HashMap<String, Object>();
          		paramMy.put("awardonId", awardonId);
                Czjawardon myorder = czjawardonService.getCzjawardon(paramMy);
                String myordernum = myorder.getExt1();
                //和自己相同的可以更新
                if(myordernum.equals(ext1)){
                	jsonResult(1,"","可以添加",1,response); 
                }else{
                  //如果跟自己的不相同
                	Map<String, Object> paramoher = new HashMap<String, Object>();
                	paramoher.put("shopId", shopId);
                	List<String> listString = czjawardonService.getCzjawardonListStringALL(paramoher);
                	boolean flag = true;
                	//循环数据库字段,如果相同,就代表有重复
                	for(String str : listString){
                		if(ext1.equals(str)){
                			flag= false;
                		}
                	}
                	if(!flag){
                		jsonResult(1,"","重复的顺序",0,response); 
                	}else{
                		jsonResult(1,"","可以添加",1,response); 
                	}
                	
                	
                }
                                                
      		}        		
     		    		      		
            } catch (Exception e) {
            jsonResult(1,"","系统异常","",response);
   			log.error("czjawardon detail error:", e); 
            throw e;
   		  }
		
	}		
	 

 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param czjawardon
	 * @return
	 */	private Map<String,Object> toMap(Czjawardon czjawardon){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(czjawardon.getAwardonId()!=null&&!czjawardon.getAwardonId().equals("")){
			map.put("awardonId", czjawardon.getAwardonId());
		}
		if(czjawardon.getProbability()!=null&&!czjawardon.getProbability().equals("")){
			map.put("probability", czjawardon.getProbability());
		}
		if(czjawardon.getCount()!=null&&!czjawardon.getCount().equals("")){
			map.put("count", czjawardon.getCount());
		}
		if(czjawardon.getThingId()!=null&&!czjawardon.getThingId().equals("")){
			map.put("thingId", czjawardon.getThingId());
		}
		if(czjawardon.getThingName()!=null&&!czjawardon.getThingName().equals("")){
			map.put("thingName", czjawardon.getThingName());
		}
		if(czjawardon.getShopId()!=null&&!czjawardon.getShopId().equals("")){
			map.put("shopId", czjawardon.getShopId());
		}
		if(czjawardon.getThingPath()!=null&&!czjawardon.getThingPath().equals("")){
			map.put("thingPath", czjawardon.getThingPath());
		}
		if(czjawardon.getCreatetime()!=null&&!czjawardon.getCreatetime().equals("")){
			map.put("createtime", czjawardon.getCreatetime());
		}
		if(czjawardon.getExt1()!=null&&!czjawardon.getExt1().equals("")){
			map.put("ext1", czjawardon.getExt1());
		}
		if(czjawardon.getExt2()!=null&&!czjawardon.getExt2().equals("")){
			map.put("ext2", czjawardon.getExt2());
		}
		if(czjawardon.getExt3()!=null&&!czjawardon.getExt3().equals("")){
			map.put("ext3", czjawardon.getExt3());
		}      
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
		
	}

	//删除更新的图片
	 public void deleteFile(String jgpName){	 
		 File f = new File(jgpName); // 输入要删除的文件位置
		 if(f.exists()){
			 f.delete();
		 }
		
	 }	


   
      
	@Resource
	private CzjawardonService czjawardonService;
	
	@Resource
	private CzjawardstockService czjawardstockService;
	
	@Resource
	private Czjtop3Service czjtop3Service;
	
	@Resource
	private CzjrouletteService czjrouletteService;		


}